package com.sk.ccflower.server.common.procManager;

import java.util.Iterator;
import java.util.TimerTask;

import org.apache.log4j.Logger;

import com.sk.ccflower.lib.define.Consts;
import com.sk.ccflower.server.lib.sysBeans.CpuLoadBean;
import com.sk.ccflower.server.lib.sysBeans.CpuStatBean;
import com.sk.ccflower.server.lib.sysBeans.ProcCpuLoadBean;
import com.sk.ccflower.server.lib.sysBeans.ProcInfoBean;
import com.sk.ccflower.server.lib.sysBeans.ProcStatBean;
import com.sk.ccflower.server.lib.sysUtils.SysResCollect;

/**
 * @author eunwoogi
 * @since 2009. 11. 11.
 */
public class ProcInfoScheduler extends TimerTask {
	
	private Logger log;
	private ProcObserver m_parent = null;
	
	public ProcInfoScheduler( ProcObserver _parent ) {
		this.log = Logger.getLogger( getClass() );
		this.m_parent = _parent;
	}
	
	@Override
	public void run() {
		try {
			collect();
		} catch ( Exception e ) {
			log.error( e );
		}
	}
	
	public void collect() {
		try {
			SysResCollect coll = new SysResCollect();
			
			/**
			 *  CPU 정보 수집(유닉스 계열의 경우 프로세스별 CPU 성능을 구하기 위해 필요함)
			 */
			CpuStatBean cpuStatPrev = this.m_parent.m_cpuStatPrev;
			CpuStatBean cpuStatCurr = coll.parseCpuStat( coll.getCpuStat() );
			CpuLoadBean cpuLoad = coll.getCpuLoad( cpuStatPrev, cpuStatCurr );
			log.debug( "TOTAL CPU(%) : "+(cpuLoad.system+cpuLoad.user) );
			
			/**
			 * 프로세스 정보 수집
			 */
			Iterator<String> it = this.m_parent.m_hashProcStatPrev.keySet().iterator();
			String key;
			ProcInfoBean infoBean;
			ProcStatBean statPrev, statCurr;
			ProcCpuLoadBean procLoad;
			while ( it.hasNext() ) {
				key = it.next();
				
				statPrev = (ProcStatBean) this.m_parent.m_hashProcStatPrev.get(key);
				
				infoBean = (ProcInfoBean) this.m_parent.m_hashProcInfo.get(key);
				
				// 프로세스가 죽었다 살면 pid가 바뀌므로 다시 pid를 가져옴
				infoBean.pid = coll.getPid( infoBean.name );
				if ( infoBean.pid == -1 ) {
					infoBean.status = Consts.DOWN;
				} else {
					infoBean.status = Consts.UP;
				}
				
				statCurr = coll.parseProcStat( coll.getProcStat(infoBean.pid) );
				
				procLoad = coll.getProcCpuLoad( statPrev, statCurr, cpuStatPrev, cpuStatCurr );
				
				infoBean.cpu = (procLoad.system + procLoad.user);
				infoBean.vmem = statCurr.vmem;
				infoBean.rmem = statCurr.rmem;
				
				log.debug( "PROCESS INFORMATION : name("+infoBean.name+") pid("+infoBean.pid+") status("+infoBean.status+") cflag("+infoBean.cflag+") cpu("+infoBean.cpu+") vmem("+infoBean.vmem+") rmem("+infoBean.rmem+")" );
				
				// 현재값을 이전값으로 저장
				statPrev.copy( statCurr );
			}
			
			// 현재값을 이전값으로 저장 : TOTAL CPU
			this.m_parent.m_cpuStatPrev.copy( cpuStatCurr );
		} catch ( Exception e ) {
			log.error( e );
		}
	}
	
}
